package com.yh.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @param
 * @author yh
 * @date 2018/4/26 16:40
 */
public class UrlFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(UrlFilter.class);
    private String contextPath;

    /**
     * @param arg0, arg1, filterChain]
     * @return void
     * @author yh
     * @date 2018/4/26 16:40
     */
    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) arg0;
        HttpServletResponse response = (HttpServletResponse) arg1;

        HttpSession session = request.getSession(true);
        /** ##### basePath路径的保存 ##### **/
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path
                + "/";
        // logger.info(basePath);
        // request.setAttribute("basePath", basePath);
        /** ##### 请求路径打印 ##### **/
        String url = request.getServletPath();
        if (url.equals(""))
            url += "/";
        // post请求编码,交给spring过滤器
        // request.setCharacterEncoding("utf-8");// 统一编码格式
        String loginName = (String) session.getAttribute("loginName");
        /** 无需验证的 */
        String[] strs = {"/css/", "/libs/", "/js/", "themes", ".css", ".jpg", ".png", "ico"}; // 路径中包含这些字符串的,可以不用用检查
        // 特殊用途的路径可以直接访问
        if (strs != null && strs.length > 0) {
            for (String str : strs) {
                if (url.indexOf(str) >= 0) {
                    filterChain.doFilter(request, response);
                    return;
                }
            }
        }
        String req_method = request.getMethod();
        /* 打印 */
//		Enumeration<?> enu = request.getParameterNames();
//		Map<String, String> parameterMap0 = new HashMap<String, String>();
//		while (enu.hasMoreElements()) {
//			String paraName = (String) enu.nextElement();
//			parameterMap0.put(paraName, request.getParameter(paraName));
//		}
//		System.out.println();
        @SuppressWarnings("rawtypes")
        Map parameterMap = request.getParameterMap();
        Map<String, String> parameterStringVal = new HashMap<String, String>();
        for (Iterator<Entry<String, String[]>> iter = parameterMap.entrySet().iterator(); iter.hasNext(); ) {
            Entry<String, String[]> element = iter.next();
            // key值
            Object strKey = element.getKey();
            // value,数组形式
            String[] value = element.getValue();
            String valStr = "";
            for (int i = 0; i < value.length; i++) {
                if (valStr.length() > 0) {
                    valStr += "," + value[i];
                } else {
                    valStr += value[i];
                }
            }
            parameterStringVal.put(strKey.toString(), valStr);
        }
        logger.info("【url日志】 UrlFilter:【" + req_method + "|" + basePath.substring(0, basePath.lastIndexOf("/")) + url
                + "】  loginName=" + loginName + " parameterMap=" + parameterStringVal);
        /** 响应计时 **/
        Long startMillis = System.currentTimeMillis();
        filterChain.doFilter(request, response);
        logger.info("【url日志】UrlFilter：【" + req_method + "|" + basePath.substring(0, basePath.lastIndexOf("/")) + url
                + "】  :耗时=" + (System.currentTimeMillis() - startMillis));
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        contextPath = arg0.getServletContext().getContextPath();
        System.out.println(contextPath + " UrlFilter：创建");
    }

    @Override
    public void destroy() {
        System.out.println(contextPath + " UrlFilter：销毁");
    }
}
